package com.bidevalution.dao.jdbc;
import com.qtp.core.model.Response;
import org.apache.log4j.Logger;

import java.sql.*;
public class ExecuteStoredProcedure {
    protected static Logger logger = Logger.getLogger(ExecuteStoredProcedure.class);
    public Connection conn;
    protected PreparedStatement ps;
    protected ResultSet rs;
    private String userName;
    private String password;
    private String driverName;
    private String url;
    public ExecuteStoredProcedure(String url, String driverName, String userName, String password) {
        this.url = url;
        this.driverName = driverName;
        this.userName = userName;
        this.password = password;
    }
    //建立连接
    public boolean getConnection(){
        try {
            Class.forName(driverName);
            conn = DriverManager.getConnection(url,userName, password);
        } catch (ClassNotFoundException e) {
            logger.error(e.getMessage());
            return false;
        } catch (SQLException e) {
            logger.error(e.getMessage());
            return false;
        }
        return true;
    }

    //增加，修改，删除
    public Response executeUpdate(String sql, Object[] params){
        getConnection();
        try {
            ps=conn.prepareStatement(sql);
            //填充占位符
            for(int i=0;i<params.length;i++){
                ps.setObject(i+1, params[i]);
            }
            ps.executeUpdate();
        } catch (SQLException e) {
            logger.error(e.getMessage());
            return Response.fail("执行失败");
        } finally {
            closeResource();
        }
        return Response.ok();
    }
    //
    //查询
    public ResultSet executeSQL(String sql, Object[] params){
        getConnection();
        try {
            ps=conn.prepareStatement(sql);
            //填充占位符
            for(int i=0;i<params.length;i++){
                ps.setObject(i+1, params[i]);
            }
            rs = ps.executeQuery();
        } catch (SQLException e) {
            logger.error(e.getMessage());
        } finally {
            closeResource();
        }
        return rs;
    }

    // 关闭资源
    public boolean closeResource() {
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                logger.error(e.getMessage());
                return false;
            }
        }
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                logger.error(e.getMessage());
                return false;
            }
        }

        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                logger.error(e.getMessage());
                return false;
            }
        }
        return true;
    }
}